<template>
  <!-- <my-big-dialog title="user group" :submit="submit"> -->
  <q-card style="max-width: 130rem;" class="card-radius overflow-hidden">
    <q-toolbar class="popup-header">
      <q-toolbar-title class="q-ma-md cap">
        {{ props.mode + ' ' + 'Competence' }}
      </q-toolbar-title>
      <q-space />
      <q-btn icon="close" size="lg" flat round dense v-close-popup />
    </q-toolbar>
    <ScrollArea :bot-margin="100">
      <q-card-section class="row justify-start">
        <q-item-label class="col-3 fal">Competence: </q-item-label>
        <q-input
          borderless
          v-model="courseCode"
          input-debounce="0"
          hide-bottom-space
          lazy-rules
          class="col-3 fal input-css"
          :dense="true"
        >
        </q-input>
      </q-card-section>
      <q-card-section  class="row col-6 justify-start items-start">
        <div class="col-3">Choose Permission:</div>
        <div class="col-9 row">
          <div class="col-12">
            <q-checkbox v-model="canDoTask" />Can do maintenance task
          </div>
          <div class="col-12">
            <q-checkbox v-model="canDoSC" />Can do maintenance by stock code
          </div>
        </div>
      </q-card-section>
      <div class="row">

         <!--  <div class="col-12">
            <q-select
              filled
              v-model="model"
              use-input
              use-chips
              multiple
              input-debounce="0"
              @new-value="createValue"
              :options="filterOptions"
              @filter="filterFn"
              style="width: 100%"
            />
          </div>
          <q-card-section class="col-12">
            <div
              style="
                border: 1px solid rgb(185, 185, 185);
                padding: 0.5rem;
                width: 100%;
                max-height: 400px;
                height: 400px;
                overflow-y: scroll;
              "
            >
              <div v-for="(permissionId, index) in permissionList" :key="index">
                <div class="row justify-between">
                  {{ perMap.get(permissionId) }}
                  <q-btn
                    dense
                    round
                    flat
                    class="del-btn"
                    @click="deleteFn(permissionId)"
                    icon="delete"
                  ></q-btn>
                </div>
              </div>
            </div>
          </q-card-section> -->

        <q-card-section  style="width: 60rem;" class="row col-6 justify-start">
          <div class="col-12">Choose Task:</div>
          <div class="col-12">
            <q-select
              filled
              v-model="taskModel"
              use-input
              use-chips
              multiple
              input-debounce="0"
              @new-value="taskCreateValue"
              :options="taskFilterOptions"
              @filter="taskFilterFn"
              style="width: 100%"
            />
          </div>
          <q-card-section class="col-12">
            <div
              style="
                border: 1px solid rgb(185, 185, 185);
                padding: 0.5rem;
                width: 100%;
                max-height: 400px;
                height: 400px;
                overflow-y: scroll;
              "
            >
              <div v-for="(item, index) in taskGroupList" :key="index">
                <div class="row justify-between">
                  {{ item.eformSchema_id + '. ' }}
                  {{ item.formNo + ' - ' }}
                  {{ item.title }}
                  <q-btn
                    dense
                    round
                    flat
                    class="del-btn"
                    @click="deleteTaskFn(item.id)"
                    icon="delete"
                  ></q-btn>
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card-section>
        <q-card-section  style="width: 60rem;" class="row col-6 justify-start">
            <div class="col-12">Choose Stock Item:</div>
          <div class="col-12">
            <q-select
              filled
              v-model="stockItemModel"
              use-input
              use-chips
              multiple
              input-debounce="0"
              @new-value="stockItemCreateValue"
              :options="stockItemFilterOptions"
              @filter="stockItemFilterFn"
              style="width: 100%"
            />
          </div>
          <q-card-section class="col-12">
            <div
              style="
                border: 1px solid rgb(185, 185, 185);
                padding: 0.5rem;
                width: 100%;
                max-height: 400px;
                height: 400px;
                overflow-y: scroll;
              "
            >
              <div v-for="(item, index) in stockItemGroupList" :key="index">
                <div class="row justify-between">
                  {{ item.stock_id + '. ' }}
                  {{ item.stock_code + ' - ' }}
                  {{ item.description }}
                  <q-btn
                    dense
                    round
                    flat
                    class="del-btn"
                    @click="deleteStockFn(item.id)"
                    icon="delete"
                  ></q-btn>
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card-section>
      </div>
    </ScrollArea>
    <q-card-actions class="justify-evenly q-pa-md">
      <q-btn label="Submit" class="default-btn" type="submit" @click="submit" />
    </q-card-actions>
  </q-card>

  <!-- </my-big-dialog> -->
</template>

<script setup lang="ts">
import {
  createGroupAndPermissionAndTask,
  getGroup,
  getTaskGroup,
  listPermission,
  updateGroupAndPermissionAndTask,
  deleteTaskGroup,
getStockItemGroup,
deleteStockGroup,
} from 'src/services/groupSettingService';
import {  ref } from 'vue';
import {  TaskGroup, StockItemGroup } from 'src/services/type';
import { useQuasar } from 'quasar';
import ScrollArea from '../ScrollArea.vue';
import { getEformSchemas } from 'src/services/eformSchemasService';
import {  getAllStockCode } from 'src/services/stockCodeService';

const props = defineProps<{
  mode: 'create' | 'edit';
  groupId?: number;
}>();

const emit = defineEmits(['submit', 'update']);

const $q = useQuasar();

const courseCode = ref('');

const permissionList = ref<number[]>([]);

const taskGroupList = ref<TaskGroup[]>([]);
const taskGroupIdList = ref<number[]>([]);

const stockItemGroupList = ref<StockItemGroup[]>([]);
const stockItemGroupIdList = ref<number[]>([]);

const canDoTask =ref(false)
const canDoSC =ref(false)

// const model = ref(null);
const taskModel = ref(null);
const stockItemModel = ref(null);

const perMap = new Map();

let stringOptions: string[] = [];
const filterOptions = ref<string[]>([]);

let taskStringOptions: string[] = [];
const taskFilterOptions = ref<string[]>([]);

let stockItemStringOptions: string[] = [];
const stockItemFilterOptions = ref<string[]>([]);

function createValue(val: string, done: any) {
  if (val.length > 2) {
    if (!stringOptions.includes(val)) {
      done(val, 'add-unique');
    }
  }
}

// function filterFn(val: string, update: any) {
//   update(() => {
//     if (val === '') {
//       filterOptions.value = stringOptions.filter((item) => {
//         const arr = item.split('. ', 1);
//         const id = parseInt(arr[0]);
//         return !permissionList.value.includes(id);
//       });
//     } else {
//       const needle = val.toLowerCase();
//       filterOptions.value = stringOptions.filter(
//         (v) => v.toLowerCase().indexOf(needle) > -1
//       );
//     }
//   });
// }

function taskCreateValue(val: string, done: any) {
  if (val.length > 2) {
    if (!taskStringOptions.includes(val)) {
      done(val, 'add-unique');
    }
  }
}

function taskFilterFn(val: string, update: any) {
  update(() => {
    if (val === '') {
      taskFilterOptions.value = taskStringOptions.filter((item) => {
        const arr = item.split('. ', 1);
        const id = parseInt(arr[0]);
        return !taskGroupIdList.value.includes(id);
      });
    } else {
      const needle = val.toLowerCase();
      taskFilterOptions.value = taskStringOptions.filter(
        (v) => v.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

function stockItemCreateValue(val: string, done: any) {
  if (val.length > 2) {
    if (!stockItemStringOptions.includes(val)) {
      done(val, 'add-unique');
    }
  }
}

function stockItemFilterFn(val: string, update: any) {
  update(() => {
    if (val === '') {
      stockItemFilterOptions.value = stockItemStringOptions.filter((item) => {
        const arr = item.split('. ', 1);
        const id = parseInt(arr[0]);
        return !stockItemGroupIdList.value.includes(id);
      });
    } else {
      const needle = val.toLowerCase();
      stockItemFilterOptions.value = stockItemStringOptions.filter(
        (v) => v.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

async function submit() {
  if (props.mode == 'create') {
    create();
  }
  if (props.mode == 'edit') {
    update();
  }
}

async function create() {
  if (courseCode.value) {
    const res = await createGroupAndPermissionAndTask(
      courseCode.value,
      canDoTask.value,
      canDoSC.value,
      taskModel.value,
      stockItemModel.value
    );
    console.log(res);
    $q.notify({
      message: 'Success',
      color: 'positive',
    });
    emit('submit');
  } else {
    $q.notify({
      message: 'Course Code  cannot empty',
      color: 'red-8',
    });
  }
}

async function update() {
  if (props.groupId) {
    const res = await updateGroupAndPermissionAndTask(
      props.groupId,
      canDoTask.value,
      canDoSC.value,
      courseCode.value,
      taskModel.value,
      stockItemModel.value
    );
    // console.log(res);
    $q.notify({
      message: 'Success',
      color: 'positive',
    });
    taskModel.value = null;
    stockItemModel.value = null;
    emit('update');
    initGroup();
    initTaskGroup();
    initStockItemGroup()
  } else {
    $q.notify({
      message: 'Course Code  cannot empty',
      color: 'red-8',
    });
  }
}

async function initEformTask() {
  taskStringOptions = [];
  const res = await getEformSchemas();
  res.data.sort((a, b) => a.id - b.id);
  if (res.data) {
    for (let data of res.data) {
      //    console.log(data);

      if (data.wi_no == '') {
        taskStringOptions.push(data.id + '. ' + data.title);
      } else {
        taskStringOptions.push(
          data.id + '. ' + data.title + ' - ' + data.formNo
        );
      }
    }
  }
  taskFilterOptions.value = taskStringOptions;
}

async function initTaskGroup() {
  if (props.groupId) {
    const res = await getTaskGroup(props.groupId);
    // console.log(res.data);
    taskGroupList.value = res.data.sort((a,b)=>a.eformSchema_id-b.eformSchema_id);
    taskGroupIdList.value = res.data.map((item: TaskGroup) => {
      return item.eformSchema_id;
    });
  }
}

async function initStockItemGroup() {
  if (props.groupId) {
    const res = await getStockItemGroup(props.groupId);
    console.log(res.data);
    stockItemGroupList.value = res.data.sort((a,b)=>a.stock_id-b.stock_id);;
    stockItemGroupIdList.value = res.data.map((item: StockItemGroup) => {
      return item.stock_id;
    });
  }
}

async function initPermission() {
  stringOptions = [];
  const res = await listPermission();
  for (let data of res) {
    // console.log(data);
    
    perMap.set(data.id, data);
    // stringOptions.push(data.name);
  }
  // filterOptions.value = stringOptions;
}

async function initGroup() {
  if (props.groupId) {
    const res = await getGroup(props.groupId);
    courseCode.value = res.data[0].name;

    for(let per of res.data[0].permissions){
      const perm = perMap.get(per)
      // console.log(perm);
      if (perm.codename == 'can_do_maintenance_task'){
        canDoTask.value = true
      }
      if (perm.codename == 'can_do_maintenance_by_stock_code'){
        canDoSC.value = true
      }
    }
  }
}

async function initStockItem() {
  stockItemStringOptions = [];
  const res = await getAllStockCode();
  console.log(res.data);
  res.data.sort((a,b)=>a.id-b.id)
  for (let data of res.data) {
    stockItemStringOptions.push(data.id + '. ' + data.stock_code + ' - ' + data.description);
  }
  stockItemFilterOptions.value = stockItemStringOptions;
}

// function deleteFn(id: number) {
//   $q.dialog({
//     title: 'Confirm',
//     message: 'Are you sure to delete this record?',
//     cancel: true,
//   }).onOk(async () => {
//     if (props.groupId) {
//       await deleteGroupPermission(id, props.groupId);
//       $q.notify({
//         message: 'success',
//         color: 'positive',
//       });
//       init();
//     }
//   });
// }

function deleteTaskFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    if (props.groupId) {
      await deleteTaskGroup(id);
      $q.notify({
        message: 'success',
        color: 'positive',
      });
      init();
    }
  });
}

function deleteStockFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    if (props.groupId) {
      await deleteStockGroup(id);
      $q.notify({
        message: 'success',
        color: 'positive',
      });
      init();
    }
  });
}
async function init() {
  initPermission();
  initEformTask();
  initTaskGroup();
  initStockItem()
  initStockItemGroup()
  if (props.mode == 'edit') {
    initGroup();
  }
}
init();
</script>
